package com.xiye.system.controller.menu;

import com.xiye.common.controller.BaseController;
import com.xiye.common.entity.*;
import com.xiye.common.util.Jurisdiction;
import com.xiye.common.util.ResultUtil;
import com.xiye.system.config.YmlConfig;
import com.xiye.system.service.menu.MenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Package com.xiye.system.controller.menu
 * @Description 菜单管理
 * @Author 西野
 * @Date 2018-07-02
 * @Version V1.0
 */
@RestController
@RequestMapping(value = "/menu")
@Api(value = "/menu", tags = "菜单管理")
@SuppressWarnings({"rawtypes", "unchecked"})
public class MenuController extends BaseController {

    @Autowired
    private MenuService menuService;
    @Autowired
    private YmlConfig ymlConfig;

    /*
     * @Author 西野
     * @Date 2018-07-06 13:34:37
     * @Description 菜单列表
     * @Param []
     * @Return java.lang.Object
     */
    @ApiOperation(value = "菜单列表", notes = "根据目录id获取菜单列表")
    @ApiImplicitParam(name = "MENU_ID", value = "目录id")
    @RequestMapping(value = "/list", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
    public Result list() {
        PageData pd = this.getPageData();
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            String MENU_ID = (null == pd.get("MENU_ID") || "".equals(pd.get("MENU_ID").toString())) ? "0" : pd.get("MENU_ID").toString();
            pd.put("MENU_ID", MENU_ID);
            List<Menu> menuList = menuService.listSubMenuByParentId(MENU_ID);
            PageData pd_new = menuService.getMenuById(pd);
            //mv.addObject("MSG", null == pd.get("MSG") ? "list" : pd.get("MSG").toString()); // MSG=change 则为编辑或删除后跳转过来的

            map.put("pd", JSONObject.fromObject(pd_new));// 传入父菜单所有信息
            map.put("MENU_ID", MENU_ID);
            map.put("MENULIST", JSONArray.fromObject(menuList));
            map.put("QX", Jurisdiction.getHC());// 按钮权限
            return ResultUtil.setRowbackResut_entity(true, 200, ymlConfig.getServer_success(), map);
        } catch (Exception e) {
            logger.error(e.toString(), e);
            return ResultUtil.setRowbackResut_entity(false, 500, ymlConfig.getServer_error(), map);
        }
    }

    /*
     * @Author 西野
     * @Date 2018-07-06 13:31:05
     * @Description 显示菜单列表ztree(菜单管理)
     * @Param [model, MENU_ID]
     * @Return java.lang.Object
     */
    @ApiOperation(value = "菜单树形", notes = "菜单树形")
    @RequestMapping(value = "/listAllMenu", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
    public Result listAllMenu(Model model, String MENU_ID) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            JSONArray arr = JSONArray.fromObject(menuService.listAllMenu("0"));
            String json = arr.toString();
            json = json.replaceAll("MENU_ID", "id").replaceAll("PARENT_ID", "pId").replaceAll("TITLE", "name").replaceAll("subMenu", "nodes").replaceAll("hasMenu", "checked").replaceAll("MENU_URL", "url");
            model.addAttribute("zTreeNodes", json);
            if (MENU_ID != null) {
                map.put("MENU_ID", MENU_ID);
            }
            map.put("zTreeNodes", json);
            return ResultUtil.setRowbackResut_entity(true, 200, ymlConfig.getServer_success(), map);
        } catch (Exception e) {
            logger.error(e.toString(), e);
            return ResultUtil.setRowbackResut_entity(false, 500, ymlConfig.getServer_error(), map);
        }
    }

    /*
     * @Author 西野
     * @Date 2018-07-06 14:32:06
     * @Description 点击树形获取编辑信息
     * @Param []
     * @Return java.lang.Object
     */
    @ApiOperation(value = "点击菜单树形", notes = "根据目录id获取菜单列表")
    @ApiImplicitParam(name = "MENU_ID", value = "目录id")
    @RequestMapping(value = "/toEdit", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
    public Result toEdit() {
        PageData pd = this.getPageData();
        Map<String, Object> map = new HashMap<String, Object>();
        String id = pd.getString("MENU_ID");
        try {
            pd = menuService.getMenuById(pd); // 读取此ID的菜单数据
            pd.put("MENU_ID", pd.get("PARENT_ID").toString()); // 用作读取父菜单信息
            pd.put("MENU_ID", id); // 复原本菜单ID
            map.put("pd", JSONObject.fromObject(pd));// 读取此ID的菜单数据
            map.put("pds", JSONObject.fromObject(menuService.getMenuById(pd)));//传入父菜单所有信息
            map.put("MENU_ID", pd.get("PARENT_ID").toString());//传入父菜单ID，作为子菜单的父菜单ID用
            map.put("QX", Jurisdiction.getHC());//按钮权限
            return ResultUtil.setRowbackResut_entity(true, 200, ymlConfig.getServer_success(), map);
        } catch (Exception e) {
            logger.error(e.toString(), e);
            return ResultUtil.setRowbackResut_entity(false, 500, ymlConfig.getServer_error(), map);
        }
    }

    /*
     * @Author 西野
     * @Date 2018-07-06 14:32:06
     * @Description 保存菜单信息
     * @Param []
     * @Return java.lang.Object
     */
    @ApiOperation(value = "保存菜单信息", notes = "根据保存菜单信息")
    @ApiImplicitParams({@ApiImplicitParam(name = "MENU_TYPE", value = "菜单类型--1：系统菜单；2：业务菜单", required = true), @ApiImplicitParam(name = "MENU_URL", value = "URL", required = true), @ApiImplicitParam(name = "MENU_STATE", value = "隐藏开关--0：隐藏；1：开启", required = true), @ApiImplicitParam(name = "MENU_ORDER", value = "排序", required = true), @ApiImplicitParam(name = "PATENT_ID", value = "上级ID", required = true), @ApiImplicitParam(name = "COMPONENT", value = "vue前端路由import路径", required = true), @ApiImplicitParam(name = "PATH", value = "vue前端路由path", required = true), @ApiImplicitParam(name = "TITLE", value = "vue前端路由title", required = true), @ApiImplicitParam(name = "NAME", value = "vue前端路由name", required = true), @ApiImplicitParam(name = "ICON", value = "vue前端路由icon", required = true)})
    @RequestMapping(value = "/addSave", method = RequestMethod.PUT, produces = "application/json;charset=utf-8")
    public Result add(Menu menu) {
        /*if (!Jurisdiction.buttonJurisdiction(menuUrl, "add")) {
            return null;
        }*/ // 校验权限
        logBefore(logger, Jurisdiction.getUsername() + "保存菜单");
        PageData pd = this.getPageData();
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            menu.setMENU_ID(String.valueOf(Integer.parseInt(menuService.findMaxId(pd).get("MID").toString()) + 1));
            menuService.saveMenu(menu); // 保存菜单
            map.put("pd", JSONObject.fromObject(menu));
            return ResultUtil.setRowbackResut_entity(true, 200, ymlConfig.getServer_success(), map);
        } catch (Exception e) {
            logger.error(e.toString(), e);
            return ResultUtil.setRowbackResut_entity(false, 500, ymlConfig.getServer_error(), map);
        }
    }

    /*
     * @Author 西野
     * @Date 2018-07-06 14:53:18
     * @Description 保存点击树形菜单
     * @Param []
     * @Return java.lang.Object
     */
    @ApiOperation(value = "点击菜单树形", notes = "根据目录id获取菜单列表")
    @ApiImplicitParams({@ApiImplicitParam(name = "MENU_ID", value = "目录id", required = true), @ApiImplicitParam(name = "MENU_URL", value = "URL", required = true), @ApiImplicitParam(name = "PARENT_ID", value = "上级ID", required = true), @ApiImplicitParam(name = "MENU_TYPE", value = "菜单类型--1：系统菜单；2：业务菜单", required = true), @ApiImplicitParam(name = "MENU_ORDER", value = "排序", required = true), @ApiImplicitParam(name = "MENU_STATE", value = "隐藏开关--0：隐藏；1：开启", required = true), @ApiImplicitParam(name = "COMPONENT", value = "vue前端路由import路径", required = true), @ApiImplicitParam(name = "PATH", value = "vue前端路由path", required = true), @ApiImplicitParam(name = "TITLE", value = "vue前端路由title", required = true), @ApiImplicitParam(name = "NAME", value = "vue前端路由name", required = true), @ApiImplicitParam(name = "ICON", value = "vue前端路由icon", required = true)})
    @RequestMapping(value = "/edit", method = RequestMethod.PUT, produces = "application/json;charset=utf-8")
    public Result edit() {
        /*if (!Jurisdiction.buttonJurisdiction(menuUrl, "edit")) {
            return null;
        }*/ // 校验权限
        PageData pd = this.getPageData();
        Map<String, Object> map = new HashMap<String, Object>();
        logBefore(logger, Jurisdiction.getUsername() + "修改菜单");
        try {
            menuService.edit(pd);
            return ResultUtil.setRowbackResut_entity(true, 200, ymlConfig.getServer_success(), map);
        } catch (Exception e) {
            logger.error(e.toString(), e);
            return ResultUtil.setRowbackResut_entity(false, 500, ymlConfig.getServer_error(), map);
        }
    }

    /*
     * @Author 西野
     * @Date 2018-07-06 14:59:05
     * @Description
     * @Param []
     * @Return java.lang.Object
     */
    @ApiOperation(value = "删除菜单", notes = "根据目录id删除菜单")
    @ApiImplicitParam(name = "MENU_ID", value = "目录id")
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE, produces = "application/json;charset=utf-8")
    public Result delete() {
        /*if (!Jurisdiction.buttonJurisdiction(menuUrl, "del")) {
            return null;
        }*/ // 校验权限
        logBefore(logger, Jurisdiction.getUsername() + "删除菜单");
        PageData pd = this.getPageData();
        String MENU_ID = pd.getString("MENU_ID");
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            if (menuService.listSubMenuByParentId(MENU_ID).size() > 0) {// 判断是否有子菜单，是：不允许删除
                map.put("success", false);
                String msg = "存在子节点不允许删除";
                return ResultUtil.setRowbackResut_entity(false, 200, msg, map);
            } else {
                menuService.deleteMenuById(MENU_ID);
                return ResultUtil.setRowbackResut_entity(true, 200, ymlConfig.getServer_success(), map);
            }
        } catch (Exception e) {
            logger.error(e.toString(), e);
            return ResultUtil.setRowbackResut_entity(false, 500, ymlConfig.getServer_error(), map);
        }
    }

    /*
     * @Author 西野
     * @Date 2018-07-06 15:03:55
     * @Description
     * @Param []
     * @Return java.lang.Object
     */
    @ApiOperation(value = "保存菜单图标", notes = "根据目录id获取菜单列表")
    @ApiImplicitParams({@ApiImplicitParam(name = "MENU_ID", value = "目录id", required = true), @ApiImplicitParam(name = "ICON", value = "VUE图标码", required = true)})
    @RequestMapping(value = "/editicon", method = RequestMethod.PUT, produces = "application/json;charset=utf-8")
    public Result editicon() {
        /*if (!Jurisdiction.buttonJurisdiction(menuUrl, "edit")) {
            return null;
        }*/ // 校验权限
        logBefore(logger, Jurisdiction.getUsername() + "修改菜单图标");
        PageData pd = this.getPageData();
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            menuService.editicon(pd);
            return ResultUtil.setRowbackResut_entity(true, 200, ymlConfig.getServer_success(), map);
        } catch (Exception e) {
            logger.error(e.toString(), e);
            return ResultUtil.setRowbackResut_entity(false, 500, ymlConfig.getServer_error(), map);
        }
    }
}
